package com.yuwenxin.servlet.controller.user;

import com.yuwenxin.bean.User;
import com.yuwenxin.service.UserService;
import com.yuwenxin.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.yuwenxin.servlet.controller.user.RegisterController.autoLogin;

public class ChangePasswordController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getSession().getAttribute("username").toString();  // 这样无法获取
        String newPassword = req.getParameter("newPassword");
        String oldPassword = req.getParameter("oldPassword");
        System.out.println("session中的username：" + username);

        Cookie[] cookies = req.getCookies();
        String changePasswordStr = null;
        for (int i=0; cookies!=null && i<cookies.length; i++){
            if ("autoLogin".equals(cookies[i].getName())){
                System.out.println("找到了autoLogin的cookie");
                changePasswordStr = cookies[i].getValue();
                break;
            }
        }
        String sessionPassword = "";
        if (changePasswordStr != null){
            String[] parts = changePasswordStr.split("-");
            sessionPassword = parts[1];
        }

        if (!oldPassword.equals(sessionPassword)){
            System.out.println("旧密码错误，请重新输入");
            req.getRequestDispatcher("/change_password.jsp").forward(req,resp);
            return;
        }

        if (oldPassword.equals(newPassword)){
            System.out.println("新密码不能与旧密码相同，请重新输入");
            req.getRequestDispatcher("/change_password.jsp").forward(req,resp);
            return;
        }
        User user;
        try {
            UserService service = new UserServiceImpl();
            user = service.findUserByName(username);
            user.setPassword(newPassword);
            int row = service.changePassword(user);
            System.out.println("修改了user共" + row + "条数据...");

            req.getSession().setAttribute("user",user);
            autoLogin(req, resp, username, newPassword);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            resp.getWriter().println("修改密码成功，3秒后跳转...");
            resp.setHeader("refresh","3;url=login.jsp");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
